package org.zwt.common.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.zwt.common.enumerate.RequestMethod;
import org.zwt.common.enumerate.HttpVersion;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Data
@NoArgsConstructor
public class HttpRequest {
    private RequestMethod method;
    private String originalUrl;
    private String url;
    private HttpVersion version;
    private Map<String, String> params = new HashMap<>();
    private Map<String, String> headers = new HashMap<>();
    private String body;

    public HttpRequest(RequestMethod method, String originalUrl, String url, HttpVersion version, Map<String, String> params, Map<String, String> headers, String body) {
        this.method = method;
        this.originalUrl = originalUrl;
        this.url = url;
        this.version = version;
        this.params = params;
        this.headers = headers;
        this.body = body;
        this.parseUrl();
    }

    ///-------------------------------------------------
    public String getHeader(String key) {
        return this.headers.get(key);
    }

    public void setHeader(String key, String value) {
        this.headers.put(key, value);
    }

    public String getParam(String key) {
        return this.params.get(key);
    }

    public void setParam(String key, String value) {
        this.params.put(key, value);
    }

    public Set<String> getHeaderNames() {
        return this.headers.keySet();
    }

    public Set<String> getParamNames() {
        return this.params.keySet();
    }

///-------------------------------------------------


    public void setOriginalUrl(String originalUrl) {
        this.originalUrl = originalUrl;
        this.parseUrl();
    }


    private void parseUrl() {
        /*
         * 从originalUrl中解析出url，params
         * */
        String[] urlAndParams = this.originalUrl.split("\\?");
        this.url = urlAndParams[0];
//      如果没有参数
        if (urlAndParams.length < 2)
            return;
//      如果有参数, 则进行解析
        String[] params = urlAndParams[1].split("&");
        for (int i = 0; i < params.length; i++) {
            String[] keyAndVlaue = params[i].split("=");
            if (keyAndVlaue.length >= 2) {
                this.params.put(keyAndVlaue[0], keyAndVlaue[1]);
            }
        }

    }

    @Override
    public String toString() {
        return "HttpRequest{" +
                "method=" + method +
                ", originalUrl='" + originalUrl + '\'' +
                ", url='" + url + '\'' +
                ", version=" + version +
                ", params=" + params +
                ", headers=" + headers +
                ", body='" + body + '\'' +
                '}';
    }
}

